//
//  GHNetworkManager.swift
//  GHWeibo
//
//  Created by LGH on 2017/8/14.
//  Copyright © 2017年 LGH. All rights reserved.
//

import UIKit
import AFNetworking

enum GHHTTPType {
    case GET
    case POST
}

class GHNetworkManager: AFHTTPSessionManager {

    static let shared = GHNetworkManager()
    lazy var userAccount = GHWeiboAccount()
    var userLogon: Bool{
        
        return userAccount.access_token != nil
    }
    
    /// 封装AFN GET和POST方法
    ///
    /// - Parameters:
    ///   - method: GET或POST
    ///   - URLString: 路径
    ///   - parameters: 请求参数
    ///   - completion: 完成回调
    
    func tokenRequest(method: GHHTTPType, URLString: String, parameters: [String: Any]?, completion:@escaping (Any?, Bool) ->()) {
        
        guard let token = userAccount.access_token else {
            print("没有token，需要登录")
            //FIXME: 发送通知，提示用户登录
            completion(nil, false)
            return
        }
        var parameters = parameters
        if parameters == nil {
            
            parameters = [String: Any]()
        }
        parameters!["access_token"] = token
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    func request(method: GHHTTPType, URLString: String, parameters: [String: Any]?, completion: @escaping (Any?, Bool) ->()) ->Void {
        
        let success = { (dataTask: URLSessionDataTask, json: Any?) ->() in
            
            completion(json, true)
        }
        
        let failure = { (dataTask: URLSessionDataTask?, error: Error) ->() in
            
            print("网络请求失败：\(error)")
            if (dataTask?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期")
                //FIXME: 发送通知
            }
            completion(nil, false)
        }
        
        if method == .GET {
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else if method == .POST {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
